package com.dyp.content_negotiation.configuration;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;

public class SnakeYamlConverter extends AbstractHttpMessageConverter<Object> {
    private final Yaml yaml;

    public SnakeYamlConverter() {
        super(new MediaType("application", "yaml"));
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
        this.yaml  = new Yaml(options);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return true; // 支持所有类型
    }

    @Override
    protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) {
        throw new UnsupportedOperationException("YAML反序列化暂未实现");
    }

    @Override
    protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException {
        try (OutputStream os = outputMessage.getBody();
             Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
             yaml.dump(object,  writer);
        }
    }
}